package com.tencreat.service.mall.impl;

import cn.hutool.json.JSONConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencreat.common.enums.BalanceBusinessType;
import com.tencreat.common.enums.BalanceTypeEnum;
import com.tencreat.common.enums.mall.AllEnum;
import com.tencreat.common.utils.RabbitSendUtils;
import com.tencreat.common.utils.StringUtils;
import com.tencreat.common.utils.http.HttpUtils;
import com.tencreat.domain.account.MallUser;
import com.tencreat.domain.mall.*;
import com.tencreat.mapper.mall.MallGoodsMapper;
import com.tencreat.service.account.IMallUserService;
import com.tencreat.service.mall.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述信息 供应链商品实现类、代采购额度恢复
 *
 * @Author yaoruiqi
 * @Company: 深圳腾创互联科技有限公司
 * @link: https://tencreat.com
 * @Date: 2023/10/25 17:10
 */

@Component("SupplyChainTask")
@Service
@Slf4j
public class IMallSupplyChainServiceImpl extends ServiceImpl<MallGoodsMapper, MallGoods> implements MallSupplyChainService {

    @Autowired
    private IMallOrderService mallOrderService;

    @Autowired
    private IMallOrderGoodsService mallOrderGoodsService;

    @Autowired
    private IMallGoodsNormsService mallGoodsNormsService;

    @Autowired
    private IMallCategoryService mallCategoryService;

    @Autowired
    private IRechargeLimitChangeService rechargeLimitChangeService;

    @Autowired
    private IMallUserService mallUserService;

    @Autowired
    private RabbitSendUtils rabbitUtils;


    //生成签名
    public static String generateSign(Map<String, Object> params, String keySecret) {
        params.remove("sign");
        params.put("keySecret", keySecret);
        JSONConfig jsonConfig = new JSONConfig();
        //对json排序
        jsonConfig.setNatureKeyComparator();
        cn.hutool.json.JSONObject json = new cn.hutool.json.JSONObject(params, jsonConfig);
        // 对字符串进行MD5签名
        String sign = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(json.toString().getBytes());
            sign = bytesToHex(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //去除keySecret
        params.remove("keySecret");
        return sign;
    }

    // 将byte数组转换成十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    //调用第三方获得数据
    private String supplyChainlist(String url, Map<String, Object> params) {
        Date date = new Date();
        long timestamp = date.getTime();
        params.put("keyId", "d96hv94s2ilaobqi");
        params.put("timeMillis", timestamp);
        params.put("sign", "");
        String sign = generateSign(params, "ad179e56a1h33vd5963426sa9216ia0l0ba1fobbba4q3ai2");
        params.put("sign", sign);
        return HttpUtils.sendPostV2(url, JSON.toJSONString(params));
    }

    /**
     * 描述信息  获取供应链全部商品列表
     *
     * @Author yaoruiqi
     * @Date: 2023/10/25 06:02
     */
    public void selectSupplyChain() {
        boolean flag = true;
        int i = 1;
        while (true) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("pageNum", i);
            map.put("pageSize", "20");
            String supplyChainGoods = supplyChainlist("http://open.hetungongying.cn/supply/open/product/queryProductAll", map);
            i++;
//            if (i>50){
//                break;
//            }
            if (StringUtils.isNotEmpty(supplyChainGoods)) {
                //将获得的供应链商品json 转成数组
                JSONObject jsonObject = JSONObject.parseObject(supplyChainGoods);
//                log.info("当前页-----{}", jsonObject.getString("pages"));
                JSONObject data = jsonObject.getJSONObject("data");
                if (data == null) {
                    break;
                }
                JSONArray records = data.getJSONArray("records");
//                log.info("当前分页总页数-----{}",data.getString("pages"));
//                log.info("当前页-----{}",data.getString("current"));
//                log.info("当前页----{}",data.getString("size"));
//                log.info("当前页-----{}",data.getString("total"));
                if (StringUtils.isEmpty(records)) {
                    break;
                }
                //存入本地数据库
                for (Object record : records) {
                    BigDecimal inventory = BigDecimal.ZERO;
                    BigDecimal miniPrice = null;
                    // 调用第三方商品详情 存sku->规格
                    MallGoods mallGoods = new MallGoods();
                    JSONObject supplyChainGood = JSONObject.parseObject(record.toString());
                    mallGoods.setChain(1);
                    mallGoods.setStore(0L);
                    mallGoods.setSupplier(0L);
//                    mallGoods.setIsOnSale(0);
                    mallGoods.setName(supplyChainGood.getString("name"));
                    //根据供应链一级、二级id 找到对应的分类
                    MallCategory mallCategory = mallCategoryService.lambdaQuery()
                            .eq(MallCategory::getChainPid, supplyChainGood.getString("firstCategoryId"))
                            .eq(MallCategory::getChainId, supplyChainGood.getString("secondCategoryId"))
                            .one();
                    if (mallCategory != null) {
                        mallGoods.setCategoryId(mallCategory.getId());
                        mallGoods.setTopCategoryId(mallCategory.getPid());
                    }
                    mallGoods.setCommoditySales(Long.valueOf(supplyChainGood.getString("sale")));
                    mallGoods.setPicUrl(supplyChainGood.getString("imgUrl"));
                    mallGoods.setGoodsSn(supplyChainGood.getString("productSn"));
                    mallGoods.setChainId(supplyChainGood.getString("id"));
                    map = new HashMap<>();
                    map.put("id", supplyChainGood.getString("id"));
                    String details = supplyChainlist("http://open.hetungongying.cn/supply/open/product/queryProductInfoNotUser", map);
                    if (StringUtils.isEmpty(details)) {
                        break;
                    } else {
                        //查询数据库中是否含有该产品
                        MallGoods one = lambdaQuery().eq(MallGoods::getChainId, supplyChainGood.getString("id")).one();

                        JSONObject data1 = JSONObject.parseObject(details);
                        if (data1 == null) {
                            break;
                        }
                        JSONObject detailsJson = data1.getJSONObject("data");
                        if (detailsJson == null) {
                            break;
                        }
                        if (one != null) {
                            Integer shelf = Integer.valueOf(detailsJson.getString("shelf"));
                            if (shelf == 0) {
                                mallGoods.setIsOnSale(shelf);
                            }
                        } else {
                            mallGoods.setIsOnSale(0);
                        }
                        String image = detailsJson.getString("image");
                        mallGoods.setGallery(image);
                        mallGoods.setVideoUrl(detailsJson.getString("productVideo"));
                        mallGoods.setDetail(detailsJson.getString("detailHtml"));
                        mallGoods.setKeywords(detailsJson.getString("keywords"));
                        mallGoods.setLogisticsId(1L);
                        mallGoods.setAuditStatus(1);
                        mallGoods.setUserId(54L);

                        if (one != null) {
                            mallGoods.setUpdateTime(LocalDateTime.now());
                            mallGoods.setId(one.getId());
                            mallGoods.updateById();
                        } else {
                            mallGoods.setCreateTime(LocalDateTime.now());
                            mallGoods.insert();
                        }

                        //获取商品规格,存入商品规格表
                        JSONArray norms = detailsJson.getJSONArray("skus");
                        if (norms.size() < 1) {
                            continue;
                        }
                        for (Object norm : norms) {
                            MallGoodsNorms mallGoodsNorms = new MallGoodsNorms();
                            JSONObject normsJson = JSONObject.parseObject(norm.toString());
                            JSONArray specDataList = normsJson.getJSONArray("specDataList");
                            for (Object spec : specDataList) {
                                JSONObject specJson = JSONObject.parseObject(spec.toString());
                                mallGoodsNorms = new MallGoodsNorms();
                                mallGoodsNorms.setGoodsId(mallGoods.getId());
                                mallGoodsNorms.setPicUrl(normsJson.getString("picUrl"));
                                mallGoodsNorms.setSupplyPrice(new BigDecimal(normsJson.getInteger("tradePrice")));
                                mallGoodsNorms.setRetailPrice(mallGoodsNorms.getSupplyPrice().multiply(new BigDecimal(3)));
                                mallGoodsNorms.setInventory(Long.valueOf(normsJson.getInteger("stock")));
                                inventory = inventory.add(BigDecimal.valueOf(Long.valueOf(normsJson.getInteger("stock"))));
                                mallGoodsNorms.setSkuId(specJson.getString("specId"));
                                if (specJson.getString("value") != null) {
                                    mallGoodsNorms.setAttribute(specJson.getString("value"));
                                } else {
                                    mallGoodsNorms.setAttribute(specJson.getString("name"));
                                }
                                mallGoodsNorms.setUserId(54L);//供应链userid，正式环境是54


                                if (mallGoodsNorms.getRetailPrice() != null) {
                                    if (miniPrice == null) {
                                        miniPrice = mallGoodsNorms.getRetailPrice();
                                        mallGoods.setSupplyPrice(mallGoodsNorms.getSupplyPrice() == null ? BigDecimal.ZERO : mallGoodsNorms.getSupplyPrice());
                                    }
                                    if (miniPrice.compareTo(mallGoodsNorms.getRetailPrice()) > 0) {
                                        miniPrice = mallGoodsNorms.getRetailPrice();
                                        mallGoods.setSupplyPrice(mallGoodsNorms.getSupplyPrice() == null ? BigDecimal.ZERO : mallGoodsNorms.getSupplyPrice());
                                    }

                                }
                                MallGoodsNorms one1 = mallGoodsNormsService.lambdaQuery().eq(MallGoodsNorms::getSkuId, mallGoodsNorms.getSkuId()).eq(MallGoodsNorms::getGoodsId, mallGoods.getId()).one();
                                if (one1 != null) {
//                                    log.info("进入规格修改---{}", mallGoodsNorms.getSkuId());
                                    mallGoodsNorms.setId(one1.getId());
                                    mallGoodsNorms.setUpdateTime(LocalDateTime.now());
                                    mallGoodsNorms.updateById();
                                } else {
                                    mallGoodsNorms.setCreateTime(LocalDateTime.now());
                                    mallGoodsNorms.insert();
                                }
                            }
                        }
                        mallGoods.setInventory(inventory.longValue());
                        mallGoods.setRetailPrice(miniPrice);
                        mallGoods.updateById();
                    }
                }
            } else {
                break;
            }
        }
    }


    /**
     * 描述信息  查询供应链分类信息
     *
     * @Author yaoruiqi
     * @Date: 2023/10/26 10:36
     */
    public void classify() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("categoryId", 0);
        String classify = supplyChainlist("http://open.hetungongying.cn/supply/open/category/queryProductTree", map);
        if (StringUtils.isNotEmpty(classify)) {
            JSONObject jsonObject = JSONObject.parseObject(classify);
            JSONArray data = jsonObject.getJSONArray("data");
            if (data != null) {
                //将查到的供应链父类存入数据库
                for (Object category : data) {
                    JSONObject categoryJson = JSONObject.parseObject(category.toString());
                    MallCategory mallCategory = new MallCategory();
                    mallCategory.setName(categoryJson.getString("name"));
                    mallCategory.setDesc(categoryJson.getString("description"));
                    mallCategory.setIconUrl(categoryJson.getString("picUrl"));
                    mallCategory.setSortOrder(categoryJson.getInteger("sort"));
                    mallCategory.setCategoryType(1L);
                    mallCategory.setStatus(true);
                    mallCategory.setCreateTime(LocalDateTime.now());
                    mallCategory.setUpdateTime(LocalDateTime.now());
                    mallCategory.setPid(0L);
                    mallCategory.setChainPid("0");
                    mallCategory.setChainId(categoryJson.getString("id"));
                    mallCategory.setHasChildren(true);
                    mallCategory.setLevel("L1");
                    //根据供应链分类id 查询数据库中有无该分类
                    MallCategory chainId = mallCategoryService.lambdaQuery().eq(MallCategory::getChainId, categoryJson.getString("id")).one();
                    if (chainId != null) {
                        mallCategory.setId(chainId.getId());
                        mallCategory.updateById();
                    } else {
                        mallCategory.insert();
                    }

                    //将查到的一级分类id取出，再次调用接口查询二级分类
                    map = new HashMap<>();
                    map.put("categoryId", categoryJson.getString("id"));
                    String classifyC = supplyChainlist("http://open.hetungongying.cn/supply/open/category/queryProductTree", map);
                    //获取子分类
                    if (StringUtils.isNotEmpty(classifyC)) {
                        JSONObject jsonObjectC = JSONObject.parseObject(classifyC);
                        JSONArray dataC = jsonObjectC.getJSONArray("data");
                        if (dataC != null) {
                            for (Object categoryC : dataC) {
                                JSONObject categoryJsonC = JSONObject.parseObject(categoryC.toString());
                                MallCategory mallCategoryC = new MallCategory();
                                mallCategoryC.setName(categoryJsonC.getString("name"));
                                mallCategoryC.setDesc(categoryJsonC.getString("description"));
                                mallCategoryC.setIconUrl(categoryJsonC.getString("picUrl"));
                                mallCategoryC.setSortOrder(categoryJsonC.getInteger("sort"));
                                mallCategoryC.setCategoryType(1L);
                                mallCategoryC.setStatus(true);
                                mallCategoryC.setCreateTime(LocalDateTime.now());
                                mallCategoryC.setUpdateTime(LocalDateTime.now());
                                mallCategoryC.setLevel("L2");
                                //通过供应链父id,获取数据库中pid
                                mallCategoryC.setPid(mallCategory.getId());
                                mallCategoryC.setChainId(categoryJsonC.getString("id"));
                                mallCategoryC.setChainPid(categoryJsonC.getString("parentId"));
                                mallCategoryC.setHasChildren(false);
                                //查询数据库中有无该分类
                                MallCategory chainIdC = mallCategoryService.lambdaQuery().eq(MallCategory::getChainId, categoryJsonC.getString("id")).one();
                                if (chainIdC != null) {
                                    mallCategoryC.setId(chainIdC.getId());
                                    mallCategoryC.updateById();
                                } else {
                                    mallCategoryC.insert();
                                }

                            }
                        }
                    }
                }
            }

        }

    }


    /**
     * 描述信息  代采购额度恢复
     *
     * @Author yaoruiqi
     * @Date: 2023/12/25 10:42
     */
    public void rechargeLimitRecover() {
        //一月一日
        int year = LocalDate.now().getYear();
        LocalDateTime first = LocalDateTime.of(year, 1, 1, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(year, 12, 31, 23, 59, 59);
        BigDecimal limit = BigDecimal.ZERO;
        List<MallUser> list = mallUserService.list();
        if (list != null && list.size() > 0) {
            for (MallUser mallUser : list) {
                //算出每个用户一年以来扣除的代采购额度
                limit = rechargeLimitChangeService.rechargeLimitRecover(first, end, mallUser.getUuid());
                if (limit.compareTo(BigDecimal.ZERO) < 0) {
                    rabbitUtils.sendBalanceMessage(mallUser.getUuid(), limit, AllEnum.BalanceChangeTypeEnums.INCOME.getType(), BalanceBusinessType.RECHARGE_RECOVER, "恢复额度", "恢复额度", BalanceTypeEnum.RECHARGE_LIMIT_CHANGE);
                }
            }
        }
    }


    /**
     * 描述信息  查询该商品是否下架
     *
     * @Author yaoruiqi
     * @Date: 2023/12/27 10:34
     */
    public void supplierChainGoods() {
        //查到所有供应链商品
        HashMap<String, Object> map = new HashMap<>();

        QueryWrapper<MallGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("chain_id");
        List<MallGoods> goods = baseMapper.selectList(queryWrapper);
//        List<MallGoods> goods = baseMapper.supplierChainGoods();
        goods.forEach(mallGoods -> {
            map.put("id", mallGoods.getChainId());
            String details = supplyChainlist("http://open.hetungongying.cn/supply/open/product/queryProductInfoNotUser", map);
            BigDecimal inventory = BigDecimal.ZERO;
            BigDecimal miniPrice = null;
            if (StringUtils.isEmpty(details)) {
                //如果该商品获取的为空，将商品设置为下架
                mallGoods.setIsOnSale(0);
                mallGoods.setRetailPrice(mallGoods.getSupplyPrice().multiply(new BigDecimal(3)));
            } else {
                JSONObject data1 = JSONObject.parseObject(details);
                if (data1 == null) {
                    mallGoods.setIsOnSale(0);
                    mallGoods.setRetailPrice(mallGoods.getSupplyPrice().multiply(new BigDecimal(3)));
                } else {
                    JSONObject detailsJson = data1.getJSONObject("data");
                    if (detailsJson == null) {
                        mallGoods.setIsOnSale(0);
                        mallGoods.setRetailPrice(mallGoods.getSupplyPrice().multiply(new BigDecimal(3)));
                    } else {
                        int shelf = Integer.parseInt(detailsJson.getString("shelf"));
                        mallGoods.setIsOnSale(shelf);
                        String image = detailsJson.getString("image");
                        mallGoods.setGallery(image);
                        mallGoods.setVideoUrl(detailsJson.getString("productVideo"));
                        mallGoods.setDetail(detailsJson.getString("detailHtml"));
                        mallGoods.setKeywords(detailsJson.getString("keywords"));
                        mallGoods.setLogisticsId(1L);
                        mallGoods.setAuditStatus(1);
                        mallGoods.setUserId(54L);
                        mallGoods.setUpdateTime(LocalDateTime.now());
                        mallGoods.updateById();


                        //获取商品规格,存入商品规格表
                        JSONArray norms = detailsJson.getJSONArray("skus");
                        if (norms.size() < 1) {
                            mallGoods.setIsOnSale(0);
                            mallGoods.setRetailPrice(mallGoods.getSupplyPrice().multiply(new BigDecimal(3)));
                        }
                        for (Object norm : norms) {
                            MallGoodsNorms mallGoodsNorms = new MallGoodsNorms();
                            JSONObject normsJson = JSONObject.parseObject(norm.toString());
                            JSONArray specDataList = normsJson.getJSONArray("specDataList");
                            for (Object spec : specDataList) {
                                JSONObject specJson = JSONObject.parseObject(spec.toString());
                                mallGoodsNorms = new MallGoodsNorms();
                                mallGoodsNorms.setGoodsId(mallGoods.getId());
                                mallGoodsNorms.setPicUrl(normsJson.getString("picUrl"));
                                mallGoodsNorms.setSupplyPrice(new BigDecimal(normsJson.getInteger("tradePrice")));
                                mallGoodsNorms.setRetailPrice(mallGoodsNorms.getSupplyPrice().multiply(new BigDecimal(3)));
                                mallGoodsNorms.setInventory(Long.valueOf(normsJson.getInteger("stock")));
                                inventory = inventory.add(BigDecimal.valueOf(Long.valueOf(normsJson.getInteger("stock"))));
                                mallGoodsNorms.setSkuId(specJson.getString("specId"));
                                if (specJson.getString("value") != null) {
                                    mallGoodsNorms.setAttribute(specJson.getString("value"));
                                } else {
                                    mallGoodsNorms.setAttribute(specJson.getString("name"));
                                }
                                mallGoodsNorms.setUserId(54L);//供应链userid，正式环境是54


                                if (mallGoodsNorms.getRetailPrice() != null) {
                                    if (miniPrice == null) {
                                        miniPrice = mallGoodsNorms.getRetailPrice();
                                        mallGoods.setSupplyPrice(mallGoodsNorms.getSupplyPrice() == null ? BigDecimal.ZERO : mallGoodsNorms.getSupplyPrice());
                                    }
                                    if (miniPrice.compareTo(mallGoodsNorms.getRetailPrice()) > 0) {
                                        miniPrice = mallGoodsNorms.getRetailPrice();
                                        mallGoods.setSupplyPrice(mallGoodsNorms.getSupplyPrice() == null ? BigDecimal.ZERO : mallGoodsNorms.getSupplyPrice());
                                    }

                                }
                                MallGoodsNorms one1 = mallGoodsNormsService.lambdaQuery().eq(MallGoodsNorms::getSkuId, mallGoodsNorms.getSkuId()).eq(MallGoodsNorms::getGoodsId, mallGoods.getId()).one();
                                if (one1 != null) {
//                                    log.info("进入规格修改---{}", mallGoodsNorms.getSkuId());
                                    mallGoodsNorms.setId(one1.getId());
                                    mallGoodsNorms.setUpdateTime(LocalDateTime.now());
                                    mallGoodsNorms.updateById();
                                } else {
                                    mallGoodsNorms.setCreateTime(LocalDateTime.now());
                                    mallGoodsNorms.insert();
                                }
                            }
                            mallGoods.setInventory(inventory.longValue());
                            mallGoods.setRetailPrice(miniPrice);
                        }
                    }
                }
            }
            List<MallGoodsNorms> goodsNormsList = mallGoodsNormsService.lambdaQuery().eq(MallGoodsNorms::getGoodsId, mallGoods.getId()).list();
            if (goodsNormsList == null || goodsNormsList.size() < 1) {
                //查到该商品是否被购买
                Integer count = mallOrderGoodsService.lambdaQuery().eq(MallOrderGoods::getGoodsSn, mallGoods.getGoodsSn()).count();
                if (count > 0) {
                    //如果已被购买，下架商品
                    mallGoods.setIsOnSale(0);
                    mallGoods.setRetailPrice(mallGoods.getSupplyPrice().multiply(new BigDecimal(3)));
                    mallGoods.updateById();
                } else {
                    //如果该商品无规格参数、且未产生订单，则删除该商品
//                        log.info("删除商品id----------------{}", mallGoods.getId());
                    mallGoods.deleteById();
                }
            } else {
                //否则更新商品
//                    log.info("更新商品id----------------{}", mallGoods.getId());
                mallGoods.updateById();
            }
        });
    }

}
